var autodb = require('../../db/auto.db')
var config = require('../../config')
var async = require('async')
var fs = require('fs');
var path = require("path");
var logger = require('../../logger');
var emit = require('../../emit');
var removefile = require("./removefile");


function parse(isMusic, file, cb) {
    async.waterfall([
        (callback) => {
            autodb.getfileinfo(isMusic, file, (err, info) => {
                callback(err, info);
            })
        },

        (info, callback) => {
            var resourcepath = isMusic ? config.musicResourcePath : config.soundResourcePath;
            var fullname = path.join(resourcepath, file + info.suffix);
            fs.exists(fullname, (exists) => {
                callback(null, exists);
            })
        },

        (exists, callback) => {
            if (exists) {
                callback(null);
            } else {
                removefile.remove(isMusic, file, false, (err) => {
                    logger.log("remove ", file, err);
                    callback(err);
                });
            }
        }
    ], (err) => {
        cb(err);
    });
}

function cleanfile(socket,isMusic) {
    async.waterfall([
        (callback) => {
            autodb.client(isMusic).smembers(config.allfile, function (err, files) {
                callback(err, files);
            });
        },
        (files, callback) => {
            async.forEach(files, (f, cb) => {
                parse(isMusic, f, (err) => {
                    cb(err);
                })
            }, (err) => {
                callback(err);
            });
        },
    ], (err) => {
        var protocol = isMusic ? 'remove-music' : 'remove-sound';
        var result = err ? false : true;
        emit.send(socket, protocol, result);
    });
}

function onsocket(socket, data) {
    cleanfile(socket,data.isMusic);
}

module.exports = {
    onsocket
}
